package top.tangyh.lamp.care.controller;

import com.github.pagehelper.util.StringUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import top.tangyh.basic.base.R;
import top.tangyh.basic.context.ContextUtil;
import top.tangyh.lamp.care.entity.BCareHandover;
import top.tangyh.lamp.care.entity.BPipeUseRecord;
import top.tangyh.lamp.care.service.*;
import top.tangyh.lamp.care.vo.query.CareHoverPageParam;
import top.tangyh.lamp.care.vo.result.*;
import top.tangyh.lamp.system.entity.tenant.DefUser;
import top.tangyh.lamp.system.service.tenant.DefUserService;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;

/**
 * @author: zqb
 * @date: 2024/7/26 09:04
 */
@Slf4j
@RequiredArgsConstructor
@Validated
@RestController
@RequestMapping("/carehandover")
@Tag(name = "护理交班")
public class CareHandOverController {

    private final BPipeUseRecordService bPipeUseRecordService;

    private final BObsvRecordService bObsvRecordService;

    private final BHl7YzYaoPlanService bHl7YzYaoPlanService;

    private final BCarePgRecordService bCarePgRecordService;

    private final DefUserService defUserService;
    
    private final BCareHandoverService bCareHandoverService;

    @GetMapping("/select/selectNotOperated")
    @Operation(summary ="查询我的未操作项目")
    public R<List<NotOperatedVO>> selectNotOperated(@Parameter(name = "hoverTime", description = "本班次时间-时间戳", required = true) @RequestParam Long hoverTime,
                                                    @Parameter(name = "patientIdent", description = "病人健康号", required = true) @RequestParam String patientIdent,
                                                    @Parameter(name = "hospitalNumber", description = "住院号", required = true) @RequestParam String hospitalNumber,
                                                    @Parameter(name = "shiftId", description = "班次id", required = true) @RequestParam Long shiftId,
                                                    @Parameter(name = "startTimestamp", description = "一个排班的开始时间", required = true) @RequestParam(required = false) Long startTimestamp,
                                                    @Parameter(name = "endTimestamp", description = "一个排班的结束时间", required = true) @RequestParam(required = false) Long endTimestamp) {
        String result = new SimpleDateFormat("yyyy-MM-dd").format(new Date(hoverTime));
        // 1，查询有效期的管道在本班次时间内到期后未拔管的管道
        List<BPipeUseRecord> list_channel = bPipeUseRecordService.selectValidityOfChannel(result, patientIdent, hospitalNumber);

        List<NotOperatedVO> listAll = new ArrayList<>();
        for (int i = 0; i < list_channel.size(); i++) {
            NotOperatedVO notOperated = new NotOperatedVO();
            notOperated.setOperatedName("管道管理");
            notOperated.setContent(list_channel.get(i).getPpName() + "今日未拔管");
            listAll.add(notOperated);
        }


        //2，观察项
        ObsvRecordQueryParam obsvRecordQueryParam = new ObsvRecordQueryParam();
        obsvRecordQueryParam.setPatientIdent(patientIdent);
        obsvRecordQueryParam.setHospitalNumber(hospitalNumber);
        obsvRecordQueryParam.setShiftCode(shiftId);
        obsvRecordQueryParam.setShiftTime(Long.valueOf(hoverTime));
        boolean resultObsv = bObsvRecordService.hasAllVal(obsvRecordQueryParam);
        //观察项里 呼吸机或者生命体征至少有一项存在未填值
        if (!resultObsv) {
            NotOperatedVO notOperated = new NotOperatedVO();
            notOperated.setOperatedName("观察项");
            notOperated.setContent("存在未填项");
            listAll.add(notOperated);
        }

        //3，执行用药  未操作的执行用药

        HandoverMedicineVo jiaoBanBO = bHl7YzYaoPlanService.getExeYaoDataByHandOver(hospitalNumber, hoverTime, startTimestamp, endTimestamp);
        if(null!=jiaoBanBO){
            if (StringUtil.isNotEmpty(jiaoBanBO.getNotOperaMsg())) {
                NotOperatedVO notOperated = new NotOperatedVO();
                notOperated.setOperatedName("执行用药");
                notOperated.setContent(jiaoBanBO.getNotOperaMsg());
                listAll.add(notOperated);
            }
        }


        //4，评估评分  ：截止到交班时间（从入院时间开始 截止到现在没填过任意一个表格就提醒），入院护理评估表未填。（提醒字段：入院护理评估表未填）
        Integer count=bCarePgRecordService.countOfPgRecord(hospitalNumber);
        if(null!=count){
            if(count==0){
                NotOperatedVO notOperated = new NotOperatedVO();
                notOperated.setOperatedName("评估评分");
                notOperated.setContent("入院护理评估表未填");
                listAll.add(notOperated);
            }
        }

        return R.success(listAll);
    }

    @GetMapping("/select/selectKeyData")
    @Operation(summary ="关键数据")
    public R<List<KeyDataVO>> selectKeyData(@Parameter(name = "hoverTime", description = "本班次时间-时间戳", required = true) @RequestParam String hoverTime,
                                               @Parameter(name = "patientIdent", description = "病人健康号", required = true) @RequestParam String patientIdent,
                                               @Parameter(name = "hospitalNumber", description = "住院号", required = true) @RequestParam String hospitalNumber,
                                               @Parameter(name = "startTimestamp", description = "一个排班的开始时间", required = true) @RequestParam(required = false) Long startTimestamp,
                                               @Parameter(name = "endTimestamp", description = "一个排班的结束时间", required = true) @RequestParam(required = false) Long endTimestamp) {
        String result = new SimpleDateFormat("yyyy-MM-dd").format(new Date(Long.valueOf(hoverTime)));
        // 此病人使用中的管道自插管时间开始截止到交班时间有效期剩余天数（仅展示填写有效期的管道）
        List<BPipeUseRecord> list_channel = bPipeUseRecordService.selectKeyData(result, patientIdent, hospitalNumber);

        List<KeyDataVO> listAll = new ArrayList<>();
        for (int i = 0; i < list_channel.size(); i++) {
            KeyDataVO keyDataVO = new KeyDataVO();
            keyDataVO.setName(list_channel.get(i).getPpName() + "有效期");
            if (list_channel.get(i).getDays() >= 0) {
                keyDataVO.setContent("剩余" + list_channel.get(i).getDays() + "天");
            } else {
                keyDataVO.setContent("过期" + Math.abs(list_channel.get(i).getDays()) + "天");
            }

            listAll.add(keyDataVO);
        }


        //呼吸机

        Integer days = bObsvRecordService.getUeDaysWithBreathe(patientIdent, Long.valueOf(hoverTime));
        if(null!=days){
            if(days>=0){
                KeyDataVO keyDataVO_hxj = new KeyDataVO();
                keyDataVO_hxj.setName("呼吸机累计使用时间");
                keyDataVO_hxj.setContent(days + "天");
                listAll.add(keyDataVO_hxj);
            }
        }



        //执行用药
        LocalDate now = LocalDate.now();
        Long currentDate = now.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli();
        HandoverMedicineVo handoverMedicineVo = bHl7YzYaoPlanService.getExeYaoDataByHandOver(hospitalNumber, currentDate, startTimestamp, endTimestamp);
//        List<ExeHandoverMedicineVo> list_zxyy = handoverMedicineVo.getCoreData();
        List<ExeHandoverMedicineVo> list_zxyy = Optional.ofNullable(handoverMedicineVo)
                .map(HandoverMedicineVo::getCoreData) // 如果 handoverMedicineVo 不为空，调用 getCoreData()
                .orElse(Collections.emptyList()); // 如果 handoverMedicineVo 或 coreData 为空，返回空列表

        if (null != list_zxyy && list_zxyy.size() > 0) {
            KeyDataVO keyDataVO = new KeyDataVO();

            for (int i = 0; i < list_zxyy.size(); i++) {
                keyDataVO.setName(list_zxyy.get(i).getMedicationName());
                keyDataVO.setContent(list_zxyy.get(i).getContent());
                listAll.add(keyDataVO);
            }
        }

        return R.success(listAll);
    }

    /**
     * 添加、修改护理交班
     */
    @PostMapping("/addOrUpdateCareHandOver")
    @Operation(summary ="添加、修改护理交班")
    public R addOrUpdateCareHandOver(@RequestBody BCareHandover careHandoverPO) throws Exception {

       // UserDto user = sysUserService.findByUserame(SecurityUtil.getCurrentUsername());
        DefUser defUser = defUserService.getByIdCache(ContextUtil.getUserId());


        //用户密码验证
//        String inputPassword = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey, careHandoverPO.getPasswordText());
//        if (!passwordEncoder.matches(inputPassword, user.getPassword())) {
//            return R.error(SysCode.passWordError);
//        }
        int resut=bCareHandoverService.addOrUpdateCareHandOver(careHandoverPO);
        if(resut>0){
            return  R.success();
        }else{
            return  R.fail(resut,"操作失败");
        }

    }

    @GetMapping("/view")
    @Operation(summary ="查看护理交班")
    public R<BCareHandover> vieCareHandOver(@Parameter(name = "id", description = "主键", required = true) @RequestParam Long id) throws Exception {
        return R.success(bCareHandoverService.getById(id));
    }

    @PostMapping("/list")
    @Operation(summary ="历史交班内容/所有")
    public R<PageOutputDTO<BCareHandoverResultVO>> listCareHandOver(@RequestBody CareHoverPageParam careHoverPageParam) {

        return R.success(bCareHandoverService.getListAll(careHoverPageParam));
    }

    @GetMapping("/list/twoday")
    @Operation(summary ="历史交班内容/展示数量为最近两天内的交班")
    public R<List<BCareHandover>> listCareHandOverTwoDay(
            @Parameter(name = "patientIdent", description = "病人识别号", required = true) @RequestParam String patientIdent,
            @Parameter(name = "hospitalNumber", description = "病人住院号", required = true) @RequestParam String hospitalNumber) {
        return R.success(bCareHandoverService.getTwoDayList(hospitalNumber, patientIdent));
    }

    @GetMapping("/delete")
    @Operation(summary ="删除")
    public R<BCareHandover> delete(@RequestParam Long id) {
        BCareHandover careHandoverPO = new BCareHandover();
        careHandoverPO.setId(id);
        careHandoverPO.setIsDeleted(1);
        return R.success(bCareHandoverService.updateById(careHandoverPO));
    }
}
